﻿angular.module('app.masterdata.customerEdit', [])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider
        .when('/cust/masterData/:num/', {
            templateUrl: 'app/masterdata/customer/customer-edit.tpl.html',

            controller: 'customerEditCtrl',
            resolve: {
                languagelist: ['baseDataProxy', function (baseDataProxy) {
                    return baseDataProxy.SysTypeDetail("013");
                }],
                isInternal: ['baseDataProxy', function (baseDataProxy) {
                    return baseDataProxy.SysTypeDetail("024");
                }],
                inUse: ['baseDataProxy', function (baseDataProxy) {
                    return baseDataProxy.SysTypeDetail("018");
                }],
                collector: ['xcceleratorProxy', function (xcceleratorProxy) {
                    return xcceleratorProxy.forXccelerator();
                }],
                custWithGroup: ['$route', 'customerProxy', 'CustomerGroupCfgProxy', '$q', function ($route, customerProxy, CustomerGroupCfgProxy, $q) {
                    var custNum = $route.current.params.num;
                    var prom = $q.defer();
                    customerProxy.queryObject({ num: custNum }).then(function (cust) {
                        CustomerGroupCfgProxy.search("$filter=(BillGroupCode eq '" + cust.billGroupCode + "')", function (group) {
                            var cWithG = [];
                            cWithG.push(cust);
                            if (group.length > 0) {
                                cWithG.push(group[0]);
                            }
                            prom.resolve(cWithG);
                        });
                    });
                    return prom.promise;
                }]
            }
        });
    } ])

.controller('customerEditCtrl', ['$scope', '$routeParams', 'customerProxy', '$routeParams', 'contactProxy', 'languagelist',
           'baseDataProxy', 'inUse', 'modalService', 'customerPaymentbankProxy', 'customerPaymentcircleProxy',
           'customerPaymentcircleProxy', 'FileUploader', 'APPSETTING', 'isInternal', 'CustomerGroupCfgProxy', 'collector', '$q',
           'custWithGroup', 'specialNotesProxy', 'siteProxy', 'dunningProxy',
            function ($scope, $routeParams, customerProxy, $routeParams, contactProxy, languagelist, baseDataProxy, inUse,
            modalService, customerPaymentbankProxy, customerPaymentcircleProxy, customerPaymentcircleProxy,
            FileUploader, APPSETTING, isInternal, CustomerGroupCfgProxy, collector, $q, custWithGroup, specialNotesProxy,
            siteProxy, dunningProxy) {
                $scope.languagelist = languagelist
                $scope.inUselist = inUse;
                $scope.internallist = isInternal;
                $scope.collectorlist = collector;
                $scope.cust = custWithGroup[0];
                $scope.group = custWithGroup[1];

                siteProxy.GetLegalEntity("type", function (legal) {
                    $scope.legallist = legal;
                }, function () {
                });

                if ($scope.cust.excludeFlg == null) {
                    $scope.cust.excludeFlg = isInternal[1].detailValue;
                } else {
                    $scope.cust.excludeFlg = $scope.cust.excludeFlg;
                }
                if ($scope.cust.collector != null) {
                    $scope.cust.collector = $scope.cust.collector;
                }

                $scope.formatLabel = function (model) {
                    // After user selection was made, We can use the group list to find out the display group name. 
                    if ($scope.groupList && $scope.groupList.$$state.value.length > 0) {
                        for (var i = 0; i < $scope.groupList.$$state.value.length; i++) {
                            if (model == $scope.groupList.$$state.value[i].billGroupCode) {
                                return $scope.groupList.$$state.value[i].billGroupName;
                            }
                        }
                    } else {
                        // This method will be called during page load, We don't have group list at that time. 
                        // have to use the group we received from the page resolver.
                        if ($scope.group) {
                            return $scope.group.billGroupName;
                        }
                    }
                };

                $scope.groupList;
                $scope.billGroupChange = function (code) {
                    $scope.groupList = CustomerGroupCfgProxy.search("$top=10&$filter=(contains(BillGroupName,'" + code + "'))")
                    return $scope.groupList;
                }

                $scope.change = function (x) {
                    angular.forEach($scope.collectorlist, function (c) {
                        if (c.eid == x) {
                            $scope.cust.collectorName = c.name;
                        }
                    });
                }

                var custNum = $routeParams.num;
                contactProxy.forCustomer(custNum, function (contactlist) {
                    $scope.conlist = contactlist;
                });
                customerPaymentbankProxy.forCustBank(custNum, function (custbanklist) {
                    $scope.banklist = custbanklist;
                });
                customerPaymentcircleProxy.forPayDate(custNum, function (paydate) {
                    $scope.paydaylist = paydate;
                });
                specialNotesProxy.forNotes(custNum, function (notes) {                  
                    if (notes != null) {
                        for (var i = 0; i < notes.length; i++) {
                            if (notes[i].legalEntity == 'Avery') {
                                $scope.notes1 = notes[i];
                            }
                            if (notes[i].legalEntity == 'Paxar - CN') {
                                $scope.notes2 = notes[i];
                            }
                            if (notes[i].legalEntity == 'Paxar - US') {
                                $scope.notes3 = notes[i];
                            }
                        }
                    } 
                })

                $scope.saveSpecialNotes = function (note, type) {
                    if ($scope.addFlg == 1 || custNum != 'newCust') {
                        var custNum = $scope.cust.customerNum;
                        var list = [];
                        list.push(custNum);
                        list.push(type);
                        list.push(note);
                        specialNotesProxy.saveNotes(list, function () {
                            alert("Success!");
                        }, function () {
                            alert("Failed!");
                        })
                    } else {
                        alert("Please Create Customer First");
                    }
                }
                //mapping id with name
                $scope.CheckType = function (obj) {
                    if (obj.toCc == "1") {
                        return "To";
                    } else {
                        return "Cc";
                    }
                }
                $scope.CheckGroupLevel = function (obj) {
                    if (obj.isGroupLevel == 1) {
                        return "Y";
                    } else {
                        return "N";
                    }
                }

                //                $('#popwindow').popover();
                /********************************Customer Attribute**************************************************/
                $scope.saveCustomer = function () {
                    $scope.cust.$saveOrUpdate(function (res) {
                        // alert("Add Success!");
                        alert(res);
                        if (res == "Add Success!") {
                            $scope.isreadonly = true;
                            $scope.addFlg = 1;
                        }
                    }, function () {
                        alert("Update Success!");
                    }, function () {
                        alert("Add Failed!");
                    }, function () {
                        alert("Update Failed");
                    });
                }

                if (custNum != 'newCust') {
                    $scope.isreadonly = true;
                } else {
                    $scope.isreadonly = false;
                }
                /********************************Contact List*******************************************************/


                $scope.AddContacterInfo = function () {
                    if ($scope.addFlg == 1 || custNum != 'newCust') {
                        var num = $scope.cust.customerNum;
                        customerProxy.queryObject({ num: num }, function (entity) {
                            var deal = entity.deal;
                            var modalDefaults = {
                                templateUrl: 'app/masterdata/contactor/contactor-edit.tpl.html',
                                controller: 'contactorEditCtrl',
                                size: 'lg',
                                resolve: {
                                    cont: function () {
                                        return new contactProxy();
                                    },
                                    num: function () {
                                        return $scope.cust.customerNum;
                                    },
                                    site: function () {
                                        return deal;
                                    },
                                    langs: function () {
                                        return $scope.languagelist;
                                    },
                                    isHoldStatus: function () {
                                        return $scope.inUselist;
                                    },
                                    legal: function () {
                                        return $scope.legallist;
                                    }
                                }, windowClass: 'modalDialog'
                            };

                            modalService.showModal(modalDefaults, {}).then(function (result) {

                                var num = $scope.cust.customerNum;
                                contactProxy.forCustomer(num, function (contactlist) {
                                    $scope.conlist = contactlist;
                                });

                            });
                        })
                    } else {
                        alert("Please Create Customer First");
                    }
                };

                $scope.EditContacterInfo = function (row) {
                    var modalDefaults = {
                        templateUrl: 'app/masterdata/contactor/contactor-edit.tpl.html',
                        controller: 'contactorEditCtrl',
                        size: 'lg',
                        resolve: {
                            cont: function () {
                                return row;
                            },
                            num: function () {
                                return $scope.cust.customerNum;
                            },
                            site: function () {
                                return $scope.cust.deal;
                            },
                            langs: function () {
                                return $scope.languagelist;
                            },
                            isHoldStatus: function () {
                                return $scope.inUselist;
                            },
                            legal: function () {
                                return $scope.legallist;
                            }
                        }, windowClass: 'modalDialog'
                    };

                    modalService.showModal(modalDefaults, {}).then(function (result) {
                        var num = $scope.cust.customerNum;
                        contactProxy.forCustomer(num, function (contactlist) {
                            $scope.conlist = contactlist;
                        });
                    });
                };
                
                $scope.Delcontacter = function (entity) {
                    var cusid= entity.id;
                    contactProxy.delContactor(cusid, function () {
                        alert("Delete Success");
                        var num = $scope.cust.customerNum;
                        contactProxy.forCustomer(num, function (contactlist) {
                            $scope.conlist = contactlist;
                        });
                    }, function () {
                        alert("Delete Error");
                    });
                };


                $scope.contactList = {
                    data: 'conlist',
                    multiSelect: false,
                    columnDefs: [
                                       { field: 'name', displayName: 'Contact Name' },
                                       { field: 'legalEntity', displayName: 'Legal Entity' },
									   { field: 'emailAddress', displayName: 'Email', width: '210' },
                                       { field: 'department', displayName: 'Department' },
                                       { field: 'title', displayName: 'Title' },
                                       { field: 'number', displayName: 'Contact Number' },
                                       { field: 'comment', displayName: 'Comment' },
                                       { field: 'communicationLanguage', displayName: 'language',
                                           cellTemplate: '<div hello="{valueMember: \'communicationLanguage\', basedata: \'grid.appScope.languagelist\'}"></div>'
                                       },
                                       {
                                           field: 'groupCode', displayName: 'To/Cc',
                                           cellTemplate: '<div style="margin-top:5px;margin-left:5px;">{{grid.appScope.CheckType(row.entity)}}</div>'
                                       },
                                       {
                                           field: 'isGroupLevel', displayName: 'Is Group Level',
                                           cellTemplate: '<div style="margin-top:5px;margin-left:5px;">{{grid.appScope.CheckGroupLevel(row.entity)}}</div>', width: '90'
                                       },
                                       { name: 'o', displayName: 'Operation', width: '90',
                                           cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a ng-click="grid.appScope.EditContacterInfo(row.entity)"  class="glyphicon glyphicon-pencil"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a ng-click="grid.appScope.Delcontacter(row.entity)" class="glyphicon glyphicon-trash"></a></div>'
                                       },
                                       
                    ]
                };

                /*****************************************Payment Bank*****************************************************/

                $scope.AddBankInfo = function () {
                    if ($scope.addFlg == 1 || custNum != 'newCust') {
                        var modalDefaults = {
                            templateUrl: 'app/masterdata/paymentbank/paymentbank-edit.tpl.html',
                            controller: 'paymentbankEditCtrl',
                            size: 'lg',
                            resolve: {
                                custInfo: function () {
                                    return customerPaymentbankProxy.queryObject({ type: "new" });
                                }, num: function () {
                                    return $scope.cust.customerNum;
                                }, flg: function () {
                                    return $scope.inUselist;
                                },
                                legal: function () {
                                    return $scope.legallist;
                                }
                            }, windowClass: 'modalDialog'
                        };

                        modalService.showModal(modalDefaults, {}).then(function (result) {
                            var num = $scope.cust.customerNum;
                            customerPaymentbankProxy.forCustBank(num, function (custbanklist) {
                                $scope.banklist = custbanklist;
                            });
                        });
                    } else {
                        alert("Please Create Customer First");
                    }
                };

                $scope.EditBankInfo = function (row) {
                    var modalDefaults = {
                        templateUrl: 'app/masterdata/paymentbank/paymentbank-edit.tpl.html',
                        controller: 'paymentbankEditCtrl',
                        size: 'lg',
                        resolve: {
                            custInfo: function () {
                                return row;
                            }, num: function () {
                                return $scope.cust.customerNum;
                            }, flg: function () {
                                return $scope.inUselist;
                            },
                            legal: function () {
                                return $scope.legallist;
                            }
                        }, windowClass: 'modalDialog'
                    };

                    modalService.showModal(modalDefaults, {}).then(function (result) {
                        var num = $scope.cust.customerNum;
                        customerPaymentbankProxy.forCustBank(num, function (custbanklist) {
                            $scope.banklist = custbanklist;
                        });
                    });
                };

                $scope.DelBankInfo = function (entity) {
                    var cusid = entity.id;
                    customerPaymentbankProxy.delPaymentBank(cusid, function () {
                        alert("Delete Success");
                        var num = $scope.cust.customerNum;
                        customerPaymentbankProxy.forCustBank(num, function (custbanklist) {
                            $scope.banklist = custbanklist;
                        });
                    }, function () {
                        alert("Delete Error");
                    });
                };

                $scope.bankList = {
                    data: 'banklist',
                    multiSelect: false,
                    columnDefs: [
                           { field: 'bankAccountName', displayName: 'Account Name' },
                           { field: 'legalEntity', displayName: 'Legal Entity' },
                           { field: 'bankName', displayName: 'Bank Name' },
                           { field: 'bankAccount', displayName: 'Bank Account' },
                           { field: 'createDate', displayName: 'Create Date' },
                           { field: 'createPersonId', displayName: 'Create Person' },
                           { field: 'flg', displayName: 'Status',
                               cellTemplate: '<div hello="{valueMember: \'flg\', basedata: \'grid.appScope.inUselist\'}"></div>'
                           },
                           { field: 'description', displayName: 'Description' },
                           { name: 'o', displayName: 'Operation', width: '90',
                               cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a ng-click="grid.appScope.EditBankInfo(row.entity)" class="glyphicon glyphicon-pencil"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a ng-click="grid.appScope.DelBankInfo(row.entity)" class="glyphicon glyphicon-trash"></a></div>'
                           }
                    ]
                };

                /****************************************Payment Circle*******************************************/
                $scope.addPaymentcircle = function () {
                    if ($scope.addFlg == 1 || custNum != 'newCust') {
                        if ($scope.paymentCircle == null || $scope.paymentCircle=="") {
                            alert("Please Select Payment Date!");
                        }
                        else {
                            if ($scope.entityFlg != null) {
                                var num = $scope.cust.customerNum;
                                var paymentCircle = [];
                                paymentCircle.push($scope.paymentCircle);
                                paymentCircle.push(num);
                                paymentCircle.push($scope.entityFlg);
                                customerPaymentcircleProxy.addPaymentCircle(paymentCircle, function (res) {
                                    //customerPaymentcircleProxy.forPayDate(num, function (paydate) {
                                    //    $scope.paydaylist = paydate;
                                    //})
                                    $scope.changeLegal($scope.entityFlg);
                                    alert(res);
                                }, function (res) {
                                    alert(res);
                                });
                            } else {
                                alert("Please Select Legal Entity First!");
                            }
                        }
                    } else {
                        alert("Please Create Customer First");
                    }
                };

                //初始化uploader

                var uploader = $scope.uploader = new FileUploader({
                    url: APPSETTING['serverUrl'] + '/api/CustomerPaymentcircle'
                });

                uploader.filters.push({
                    name: 'customFilter',
                    fn: function (item /*{File|FileLikeObject}*/, options) {
                        return this.queue.length < 10;
                    }
                });

                // CALLBACKS
                uploader.onSuccessItem = function (fileItem, response, status, headers) {
                    alert(response);
                    var num = $scope.cust.customerNum;
                    $scope.changeLegal($scope.entityFlg);
                };
                uploader.onErrorItem = function (fileItem, response, status, headers) {
                    alert(response);
                };

                $scope.addFileCircle = function () {
                    if ($scope.addFlg == 1 || custNum != 'newCust') {                   
                        if (uploader.queue[2] == null) {
                            alert("Please Select File");
                        } else {
                            if ($scope.entityFlg != null) {
                                if ((uploader.queue[2]._file.name.toString().toUpperCase().split(".").length > 1)
                                && uploader.queue[2]._file.name.toString().toUpperCase().split(".")[1]!= "CSV") {
                                    alert("File format is not correct !");
                                    return;
                                }
                                var num = $scope.cust.customerNum;
                                var legal = $scope.entityFlg;
                                uploader.queue[2].url = APPSETTING['serverUrl'] + '/api/CustomerPaymentcircle?customerNum=' + num + '&legal=' + legal;
                                uploader.uploadAll();
                            } else {
                                alert("Please Select Legal Entity First!");
                            }
                        }
                    } else {
                        alert("Please Create Customer First");
                    }
                }

                $scope.DelPaymentcircle = function (entity) {
                    var cusid = entity.id;
                    customerPaymentcircleProxy.delPaymentCircle(cusid, function () {
                        alert("Delete Success");
                        var num = $scope.cust.customerNum;
                        $scope.changeLegal($scope.entityFlg);
                    }, function () {
                        alert("Delete Error");
                    });
                };

                $scope.paydayList = {
                    data: 'paydaylist',
                    multiSelect: false,
                    //  enableFullRowSelection: true,
                    columnDefs: [
                           { field: 'sortId', displayName: '#' },
                           { field: 'legalEntity', displayName: 'Legal Entity' },
                           { field: 'paymentDay', displayName: 'Payment Day' , cellFilter: 'date:\'yyyy-MM-dd\'' },
                           //{ field: 'paymentWeek', displayName: 'Week Day',
                           //    cellTemplate: '<div hello="{valueMember: \'paymentWeek\', basedata: \'grid.appScope.weeklist\'}"></div>'
                           //},
                           { field: 'weekDay', displayName: 'Week Day' },
                           { name: 'o', displayName: 'Operation', width: '90',
                               cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a ng-click="grid.appScope.DelPaymentcircle(row.entity)" class="glyphicon glyphicon-trash"></a></div>'
                           }
                    ]
                };

                $scope.changeLegal = function (legal) {
                  
                    customerPaymentcircleProxy.searchPaymentCircle(custNum, legal
                        , function (paydate) {                            
                            $scope.paydaylist = paydate;
                            uploader.queue[2]= null;
                            document.getElementById("uploadCalendar").value="";
                        },
                        function () {
                        });
                }

                //*************************** Dunning*************************************************
                $scope.dunningList = {
                    data: 'dunninglist',
                    multiSelect: false,
                    columnDefs: [
                           { field: 'legalEntity', displayName: 'Legal Entity' },
                           { field: 'firstInterval', displayName: 'First Interval' },
                           { field: 'secondInterval', displayName: 'Second Interval'},
                           { field: 'paymentTAT', displayName: 'Payment TAT'  },
                           { field: 'riskInterval', displayName: 'Risk Interval' },
                           { field: 'description', displayName: 'Description' },
                           { name: 'o', displayName: 'Operation', width: '90',
                               cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a ng-click="grid.appScope.EditConfig(row.entity)" class="glyphicon glyphicon-pencil"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></div>'
                           }
                    ]
                };

                dunningProxy.forConfig(custNum, function (config) {
                    $scope.dunninglist = config;
                })
              
                $scope.getUnAddLegal = function () {
                    var restlist = [];
                    if ($scope.dunninglist.length != 0) {                       
                        angular.forEach($scope.legallist, function (row1) {
                            var k = 0;
                            angular.forEach($scope.dunninglist, function (row2) {
                                if (row1.legalEntity == row2.legalEntity) {
                                    k = 1;
                                }  
                            })
                            if (k == 0) {
                                restlist.push(row1);
                            }
                        })
                        return restlist;
                    } else {
                        return $scope.legallist;
                    }
                }
      
                $scope.AddConfig = function () {
                    var rest = $scope.getUnAddLegal;                   
                    if ($scope.addFlg == 1 || custNum != 'newCust') {
                        if ($scope.dunninglist.length != $scope.legallist.length) {
                            var modalDefaults = {
                                templateUrl: 'app/masterdata/dunning/dunning-edit.tpl.html',
                                controller: 'dunningEditCtrl',
                                resolve: {
                                    config: function () {
                                        return new dunningProxy();
                                    },
                                    num: function () {
                                        return $scope.cust.customerNum;
                                    },
                                    legal: rest
                                }, windowClass: 'modalDialog'
                            };
                            modalService.showModal(modalDefaults, {}).then(function (result) {
                                var num = $scope.cust.customerNum;
                                dunningProxy.forConfig(num, function (config) {
                                    $scope.dunninglist = config;
                                })
                            });
                        } else {
                            alert("All Legal Entity have already add!");
                        }
                    } else {
                        alert("Please Create Customer First");
                    }                  
            };

                $scope.EditConfig= function (row) {
                    var modalDefaults = {
                            templateUrl: 'app/masterdata/dunning/dunning-edit.tpl.html',
                            controller: 'dunningEditCtrl',
                            resolve: {
                                    config: function () {
                                        return row;
                                    },
                                    num: function () {
                                        return $scope.cust.customerNum;
                                     },
                                    legal: function () {
                                          var currlegallist = [];
                                            for (var i = 0; $scope.legallist.length;i++)
                                            if ($scope.legallist[i].legalEntity == row.legalEntity) {
                                                currlegallist.push($scope.legallist[i])
                                                return currlegallist;
                                            }
                                        }
                        }, windowClass: 'modalDialog'
                     };
                    modalService.showModal(modalDefaults, {}).then(function (result) {
                        var num = $scope.cust.customerNum;
                        dunningProxy.forConfig(num, function (config) {
                            $scope.dunninglist = config;
                    })
                });
            };


                //******************************************************************************************

            } ]);
